package cn.linkstudy.controller;

import cn.linkstudy.common.Result;
import cn.linkstudy.entity.User;
import cn.linkstudy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody User user) {
        try {
            boolean success = userService.register(user);
            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("userId", user.getId());
                data.put("username", user.getUsername());
                data.put("phone", user.getPhone());
                return Result.success("注册成功", data);
            } else {
                return Result.error("用户名或手机号已存在");
            }
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam Long userId) {
        try {
            User user = userService.getById(userId);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/sendCode")
    public Result<?> sendCode(@RequestBody Map<String, String> body) {
        System.out.println("=== UserController.sendCode called ===");
        System.out.println("Request body: " + body);
        String phone = body.get("phone");
        if (phone == null || phone.isEmpty()) {
            return Result.error("手机号不能为空");
        }
        try {
            System.out.println("Sending SMS code to phone: " + phone);
            userService.sendSmsCode(phone);
            System.out.println("SMS code sent successfully");
            return Result.success("验证码已发送");
        } catch (Exception e) {
            System.out.println("SMS code sending failed: " + e.getMessage());
            e.printStackTrace();
            return Result.error("发送失败: " + e.getMessage());
        }
    }

    /**
     * 手机号+验证码登录
     */
    @PostMapping("/loginByCode")
    public Result<Map<String, Object>> loginByCode(@RequestBody Map<String, String> body) {
        String phone = body.get("phone");
        String code = body.get("code");
        if (phone == null || code == null) {
            return Result.error("手机号和验证码不能为空");
        }
        try {
            String token = userService.loginByPhoneCode(phone, code);
            if (token != null) {
                User user = userService.findByPhone(phone);
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("userId", user.getId());
                data.put("username", user.getUsername());
                data.put("phone", user.getPhone());
                return Result.success("登录成功", data);
            } else {
                return Result.error("验证码错误或已失效");
            }
        } catch (Exception e) {
            if (e.getMessage().contains("未注册")) {
                return Result.error("手机号未注册，请先注册");
            }
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    @PostMapping("/updateUsername")
    public Result<?> updateUsername(@RequestBody Map<String, Object> body) {
        if (body == null || body.get("userId") == null || body.get("username") == null) {
            return Result.error("参数缺失");
        }
        Long userId;
        try {
            userId = Long.valueOf(body.get("userId").toString());
        } catch (Exception e) {
            return Result.error("userId格式错误");
        }
        String username = body.get("username").toString();
        User user = userService.getById(userId);
        if (user == null)
            return Result.error("用户不存在");
        user.setUsername(username);
        userService.updateById(user);
        return Result.success("用户名已更新");
    }

    @PostMapping("/updateAvatarColor")
    public Result updateAvatarColor(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        String avatarColor = params.get("avatarColor").toString();
        boolean success = userService.updateAvatarColor(userId, avatarColor);
        if (success) {
            return Result.success("头像颜色已更新");
        } else {
            return Result.error("保存失败");
        }
    }
}